#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<signal.h>
#include<pthread.h>

const int size = 1024;
int *num;
char *share_addr;
pthread_mutex_t *mutex;

char *new_shared_memory(int len)
{
	/*	void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
	*/
	char *addr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	if (addr == MAP_FAILED)
	{
		perror("mmap error");
		exit(1);
	}
	return addr;
}

void init()
{
	num = (int*) new_shared_memory(4);	
	*num = 0;
	mutex = (pthread_mutex_t *) new_shared_memory(sizeof(pthread_mutex_t));
	pthread_mutex_init(mutex, NULL);
	share_addr = new_shared_memory(size);
}

void parent_doit()
{
	while (1)
	{
		pthread_mutex_lock(mutex);
		*num = read(0, share_addr, size);
		if (share_addr[0] == 'q')
		{
			if (kill(0, 3) < 0)
			{
				perror("kill child process error");
			}
			exit(0);
		}
		pthread_mutex_unlock(mutex);
		sleep(1);
	}
}

void child_signal(int signo)
{
	if (signo == 3)
	{
		printf("parent signal receive by child\n");
		exit(0);
	}
}
void child_doit()
{
	signal(3, child_signal);
	while (1)
	{
		pthread_mutex_lock(mutex);
		if (*num > 0) 
		{
			write(1, "child write:", 12);
			write(1, share_addr, *num);
		}
		*num = 0;
		pthread_mutex_unlock(mutex);
		sleep(1);
	}
}

int main()
{
	pid_t pid;
	init();
	if ((pid = fork()) < 0)	
	{
		perror("fork error");
		exit(3);
	} else if (pid == 0)
	{
		child_doit();
		exit(0);
	}

	parent_doit();
	return 0;
}

